<?php

namespace App\Http\Requests;

use App\Models\ProductSku;
//use Illuminate\Foundation\Http\FormRequest;

class AddCartRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
//    public function authorize()
//    {
//        return false;
//    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'amount'=>'required|integer|min:1',
            'sku_id'=>[
                'required',
                function($attribute, $value, $fail){
                    if(!$sku=ProductSku::find($value))
                        return $fail('商品不存在');
                    else if(($product=$sku->product) && !$product->on_sale)
                        return $fail('商品未上架');
                    else if(!$stock=$sku->stock)
                        return $fail('商品库存为0');
                    else if(($amount=request('amount')) && $amount>$stock)
                        return $fail('商品库存不足');
                }
            ]
        ];
    }
    public function attributes(){
        return [
            'amount'=>'商品数量',
        ];
    }
    public function messages(){
        return [
            'sku_id.required'=>'请选择商品规格'
        ];
    }
}
